package com.woniu.inlet.timer;

import com.woniu.adapter.FixedCurrentIncomeAdapter;
import com.woniu.outlet.mysql.po.FixedCurrentIncomeMySQL;
import com.woniu.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 活期产品收益每日0:03确认收益
 */
@Component
@Slf4j
public class CurrentIncomeTimer {

    @Autowired
    private FixedCurrentIncomeAdapter currentIncomeAdapter;

    /**
     *
     */
    @Scheduled(cron = "0 2 0 ? * *") //每天0:02分 确认昨日的收益
    public void currentIncome() {
        log.debug("活期产品确认收益开始，开始时间{}", DateUtil.getBuyTime());
        //得到今日日期
        String todayDate = DateUtil.getSendDate();
        String[] split = todayDate.split("-");
        //得到 年 月 日
        int year = Integer.parseInt(split[0]);
        int month = DateUtil.getStringFormatToInt(split[1]);
        int day = DateUtil.getStringFormatToInt(split[2])-1;
        String date = DateUtil.getUpdateBeforeTime(year,month,day);
        log.debug("今日日期{}，要确认收益的日期{}",todayDate,date);
        //查询所有活期产品
        List<FixedCurrentIncomeMySQL> allCurrent = currentIncomeAdapter.getAllCurrent(date);
        log.debug("要确认收益的个人活期产品共有{}条", allCurrent.size());
        if (allCurrent.size() == 0) return;
        for (FixedCurrentIncomeMySQL c : allCurrent) {
            //活期理财产品持有到期收益率计算公式:本金*持有天数*(年化收益率/365天)。
            BigDecimal rate = c.getRateOfReturn().divide(new BigDecimal("36500"), 5, BigDecimal.ROUND_DOWN);
            log.debug("该[{}]活期产品的年化收益率为【{}%】，算得的日利率为{}", c.getCodeId(), c.getRateOfReturn(), rate);
            log.debug("当前用户{}，购买该产品总金额为{}元，目前总收益为{}元", c.getUserId(), c.getTotalPrincipal(), c.getIncome());
            BigDecimal income1 = c.getTotalPrincipal().multiply(new BigDecimal(c.getHoldDay()));
            BigDecimal income2 = income1.multiply(rate);
            BigDecimal income3 = income2.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
            c.setIncome(c.getIncome().add(income3));
            log.debug("持有该产品{}天，计算后的总收益为{}", c.getHoldDay(), c.getIncome());
            c.setHoldDay(c.getHoldDay() + 1);
            currentIncomeAdapter.updateById(c);
            log.debug("持有天数+1={}", c.getHoldDay());
        }
        log.debug("活期产品确认收益完成,共确认{}条", allCurrent.size());
    }
}
